"""
Case Type   : 基础功能
Case Name   : 发布端备升主后，修改删除发布及对应订阅
Create At   : 2022/11/09
Owner       : opentestcase026
Description :
    1.发布端开启逻辑复制槽主备同步
    2.分别在两个集群创建两张表
    3.创建发布订阅
    4.发布端表中插入数据
    5.查询订阅端数据是否同步
    6.发布端备升主
    7.修改发布名、订阅端更新发布名
    8.发布端更新数据
    9.订阅端查询数据是否更新
    10.删除发布订阅
    11.发布端删除数据
    12.订阅端查询数据是否更新
    13.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.数据同步
    6.成功
    7.成功
    8.成功
    9.数据同步
    10.成功
    11.成功
    12.数据不同步
    13.成功
History     :
"""

import os
import time
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.com_pub = Common()
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.std_userdb_pub = Node(node='Standby1DbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_pub_std = CommonSH('Standby1DbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.tb_name = ['t_pubsub_0207_1', 't_pubsub_0207_2']
        self.subname = 'sub_pubsub_0207'
        self.pubname = 'pub_pubsub_0207'
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        self.wal_level = self.com_pub.show_param("wal_level")
        text = '-----查询集群状态，配置白名单，发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res1 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host replication {self.pri_userdb_sub.db_user} '
            f'{self.pri_userdb_sub.db_host}/32 sha256')
        self.log.info(guc_res1)
        self.assertTrue(guc_res1, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res2 = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32 sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res2)
        self.assertTrue(guc_res2, f'订阅端配置白名单失败:{text}')

    def test_pub_sub(self):
        text = "-----step1:发布端开启逻辑复制槽主备同步;expect:成功-----"
        self.log.info(text)
        self.enable_slot_log = self.com_pub.show_param("enable_slot_log")
        if 'on' != self.enable_slot_log:
            result = self.commsh_pub.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG,
                'enable_slot_log=on')
            self.assertTrue(result, f'设置enable_slot_log失败')

        text = "-----step2:分别在两个集群创建两张表;expect:成功-----"
        self.log.info(text)
        create_tb = f'''drop table if exists {self.tb_name[0]}, 
        {self.tb_name[1]} cascade;
        create table {self.tb_name[0]}(
        id1 int primary key, id2 int, id3 int) with (segment=on);
        create table {self.tb_name[1]}(
        id int primary key constraint id_nn not null,
        use_filename varchar2(20), filename varchar2(255),
        text varchar2(2000)) partition by range(id)(
        partition p1 values less than(30),
        partition p2 values less than(60),
        partition p3 values less than(90),
        partition p4 values less than(maxvalue));'''
        pub_res = self.commsh_pub.execut_db_sql(create_tb,
                                                sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertEqual(pub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         4, f'执行失败:{text}')
        sub_res = self.commsh_sub.execut_db_sql(
            create_tb, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertEqual(sub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         4, f'执行失败:{text}')

        text = "-----step3:创建发布订阅;expect:成功-----"
        self.log.info(text)
        create_pub = f"drop publication if exists {self.pubname};" \
                     f"create publication {self.pubname} for all tables;"
        pub_res = self.commsh_pub.execut_db_sql(create_pub,
                                                sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertIn(self.constant.create_pub_succ_msg, pub_res,
                      f'执行失败:{text}')
        guc_res = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, guc_res,
                      f'执行失败:{text}')
        create_sub = f"drop subscription if exists {self.subname};" \
                     f"create subscription {self.subname} connection " \
                     f"'host={self.pri_userdb_pub.db_host} " \
                     f"port={self.port} user={self.pri_userdb_pub.db_user} " \
                     f"dbname={self.pri_userdb_pub.db_name} " \
                     f"password={self.pri_userdb_pub.ssh_password}' " \
                     f"publication {self.pubname} with (binary=True);"
        sub_res = self.commsh_sub.execut_db_sql(
            create_sub, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertIn(self.constant.create_sub_succ_msg, sub_res,
                      f'执行失败:{text}')

        text = "-----step4:发布端表中插入数据;expect:成功-----"
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name[0]} values(" \
                  f"generate_series(1,1000), 1, 1);" \
                  f"insert into {self.tb_name[1]} values(" \
                  f"generate_series(1,1000), 'first', '%一', '');"
        pub_result = self.commsh_pub.execut_db_sql(sql_cmd,
                                                   sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertEqual(pub_result.count(self.constant.INSERT_SUCCESS_MSG), 2,
                         f'执行失败:{text}')

        text = "-----step5:查询订阅端数据是否同步;expect:数据同步-----"
        self.log.info(text)
        self.commsh_pub.check_sub_consistency(
            self.subname, self.user_param_pub, 20)
        sub_select = f"select count(*) from {self.tb_name[0]};" \
                     f"select count(*) from {self.tb_name[1]};"
        select_res = self.commsh_sub.execut_db_sql(
            sub_select, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(select_res)
        self.assertEqual(select_res.count('1000'), 2, f'执行失败:{text}')

        text = "-----step6:发布端备升主;expect:成功-----"
        self.log.info(text)
        stop_primary = self.commsh_pub.stop_db_instance()
        self.log.info(stop_primary)
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, stop_primary,
                      f'stop主机失败:{text}')
        pub_result = self.commsh_pub_std.execute_gsctl(
            'failover', self.constant.FAILOVER_SUCCESS_MSG)
        self.log.info(pub_result)
        self.assertTrue(pub_result, f'执行失败:{text}')
        start_primary = self.commsh_pub.start_db_instance(mode="standby")
        self.log.info(start_primary)
        self.assertIn('server started', start_primary,
                      f'start主机失败:{text}')

        text = "-----step7:修改发布名，订阅端更新发布名;expect:成功-----"
        self.log.info(text)
        pub_res = self.commsh_pub_std.execut_db_sql(
            f"alter publication {self.pubname} rename to new_{self.pubname};",
            self.user_param_sub)
        self.log.info(pub_res)
        self.assertIn(self.constant.alter_pub_succ_msg, pub_res,
                      f'修改发布名失败:{text}')
        sub_res = self.commsh_sub.execut_db_sql(
            f"alter subscription {self.subname} "
            f"set publication new_{self.pubname};",
            self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertIn(self.constant.alter_sub_succ_msg, sub_res,
                      f'订阅更新发布名失败:{text}')

        text = "-----step8:发布端更新数据;expect:成功-----"
        self.log.info(text)
        upd_sql = f"update {self.tb_name[0]} set id2=999;" \
                  f"update {self.tb_name[1]} set filename='new';"
        upd_res = self.commsh_pub_std.execut_db_sql(upd_sql,
                                                    self.user_param_sub)
        self.log.info(upd_res)
        self.assertEqual(upd_res.count(self.constant.UPDATE_SUCCESS_MSG), 2,
                         f'执行失败:{text}')

        text = "-----step9:订阅端查询数据是否同步;expect:数据同步-----"
        self.log.info(text)
        time.sleep(6)
        select_sql = f"alter subscription {self.subname} refresh " \
                     f"publication;" \
                     f"select * from {self.tb_name[0]} limit 5;" \
                     f"select * from {self.tb_name[1]} limit 5;"
        select_res = self.commsh_sub.execut_db_sql(
            select_sql, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(select_res)
        self.assertIn(self.constant.alter_sub_succ_msg, sub_res,
                      f'刷新订阅失败:{text}')
        self.assertEqual(select_res.count('999'), 5, f'执行失败:{text}')
        self.assertEqual(select_res.count('new'), 5, f'执行失败:{text}')

        text = "-----step10:删除发布订阅;expect:成功-----"
        self.log.info(text)
        drop_sub = f"drop subscription if exists {self.subname};"
        sub_res = self.commsh_sub.execut_db_sql(
            drop_sub, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertIn(self.constant.drop_sub_succ_msg, sub_res,
                      f'删除订阅失败:{text}')
        drop_pub = f"drop publication if exists new_{self.pubname};"
        pub_res = self.commsh_pub_std.execut_db_sql(
            drop_pub, sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertIn(self.constant.drop_pub_succ_msg, pub_res,
                      f'删除发布失败:{text}')

        text = "-----step11:发布端删除表数据;expect:成功-----"
        self.log.info(text)
        del_sql = f"delete from {self.tb_name[0]};" \
                  f"delete from {self.tb_name[1]};"
        del_res = self.commsh_pub_std.execut_db_sql(del_sql,
                                                    self.user_param_sub)
        self.log.info(del_res)
        self.assertEqual(del_res.count(self.constant.DELETE_SUCCESS_MSG), 2,
                         f'执行失败:{text}')

        text = "-----step12:订阅端查询数据是否更新;expect:数据不同步-----"
        self.log.info(text)
        sub_select_res = self.commsh_sub.execut_db_sql(
            sub_select, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_select_res)
        self.assertEqual(sub_select_res.count('1000'), 2, f'执行失败:{text}')

    def tearDown(self):
        text = "-----step13:清理环境;expect:成功-----"
        self.log.info(text)
        pubswi_res = self.commsh_pub.execute_gsctl(
            'switchover', self.constant.SWITCH_SUCCESS_MSG)
        self.log.info(pubswi_res)
        pubref_res = self.commsh_pub.exec_refresh_conf()
        self.log.info(pubref_res)
        drop_sub = f"drop subscription if exists {self.subname};"
        drop_sub_res = self.commsh_sub.execut_db_sql(
            drop_sub, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_sub_res)
        drop_pub = f"drop publication if exists {self.pubname}, " \
                   f"new_{self.pubname} cascade;"
        drop_pub_res = self.commsh_pub.execut_db_sql(
            drop_pub, sql_type=self.user_param_pub)
        self.log.info(drop_pub_res)
        drop_tb = f"drop table if exists {self.tb_name[0]}, " \
                  f"{self.tb_name[1]} cascade;"
        pub_droptb = self.commsh_pub.execut_db_sql(
            drop_tb, sql_type=self.user_param_pub)
        self.log.info(pub_droptb)
        sub_droptb = self.commsh_sub.execut_db_sql(
            drop_tb, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_droptb)
        guc_res1 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host replication {self.pri_userdb_sub.db_user} '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(guc_res1)
        guc_res2 = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host replication {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res2)
        res_wal = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(res_wal)
        recov_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'enable_slot_log={self.enable_slot_log}')
        pub_restartdb = self.commsh_pub.restart_db_cluster()
        self.assertTrue(pub_restartdb, f'发布端重启数据库失败:{text}')
        self.assertTrue(recov_res, f'恢复enable_slot_log失败')
        self.assertTrue(pubswi_res, f'执行失败:{text}')
        self.assertTrue(pubref_res, f'执行失败:{text}')
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_res,
                      f'删除订阅失败:{text}')
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_res,
                      f'删除发布失败:{text}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, sub_droptb,
                      f'订阅端删除表失败:{text}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, pub_droptb,
                      f'发布端删除表失败:{text}')
        self.assertTrue(guc_res1, f'发布端删除白名单失败:{text}')
        self.assertTrue(guc_res2, f'订阅端删除白名单失败:{text}')
        self.assertTrue(res_wal, f'发布端恢复wal_level参数失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
